<?php
session_start();

if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

// 检查并初始化文件
function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        file_put_contents($filename, $defaultContent);
    }
    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    return is_array($data) ? $data : json_decode($defaultContent, true);
}

$currentUser = $_SESSION['username'];
$fromUser = $_POST['from_user'] ?? '';
$action = $_POST['action'] ?? '';

if (empty($fromUser) || !in_array($action, ['accept', 'reject'])) {
    die('无效的请求！');
}

// 加载好友请求列表
$requestsFile = __DIR__ . "/user/$currentUser/requests.json";
$requests = ensureFile($requestsFile);

// 移除处理的好友请求
$requests = array_filter($requests, fn($req) => $req['from'] !== $fromUser);
file_put_contents($requestsFile, json_encode(array_values($requests)));

// 如果同意请求
if ($action === 'accept') {
    // 更新好友列表
    $currentFriendsFile = __DIR__ . "/user/$currentUser/friends.json";
    $currentFriends = ensureFile($currentFriendsFile);
    if (!in_array($fromUser, $currentFriends)) {
        $currentFriends[] = $fromUser;
        file_put_contents($currentFriendsFile, json_encode($currentFriends));
    }

    $fromFriendsFile = __DIR__ . "/user/$fromUser/friends.json";
    $fromFriends = ensureFile($fromFriendsFile);
    if (!in_array($currentUser, $fromFriends)) {
        $fromFriends[] = $currentUser;
        file_put_contents($fromFriendsFile, json_encode($fromFriends));
    }

    // 创建私聊会话
    $chatId = md5($currentUser . $fromUser); // 唯一聊天标识符
    $currentChatsFile = __DIR__ . "/user/$currentUser/chats.json";
    $currentChats = ensureFile($currentChatsFile);
    if (!array_filter($currentChats, fn($chat) => $chat['id'] === $chatId)) {
        $currentChats[] = [
            'id' => $chatId,
            'type' => 'private',
            'name' => $fromUser,
            'unread' => false
        ];
        file_put_contents($currentChatsFile, json_encode($currentChats));
    }

    $fromChatsFile = __DIR__ . "/user/$fromUser/chats.json";
    $fromChats = ensureFile($fromChatsFile);
    if (!array_filter($fromChats, fn($chat) => $chat['id'] === $chatId)) {
        $fromChats[] = [
            'id' => $chatId,
            'type' => 'private',
            'name' => $currentUser,
            'unread' => false
        ];
        file_put_contents($fromChatsFile, json_encode($fromChats));
    }

    // 系统消息通知
    $systemMessagesFile = __DIR__ . "/user/$fromUser/system_messages.json";
    $systemMessages = ensureFile($systemMessagesFile);
    $systemMessages[] = [
        'type' => 'friend_response',
        'from' => $currentUser,
        'content' => "$currentUser 已接受您的好友请求。",
        'status' => 'processed',
        'timestamp' => date('Y-m-d H:i:s')
    ];
    file_put_contents($systemMessagesFile, json_encode($systemMessages));
}

// 如果拒绝请求
if ($action === 'reject') {
    $systemMessagesFile = __DIR__ . "/user/$fromUser/system_messages.json";
    $systemMessages = ensureFile($systemMessagesFile);
    $systemMessages[] = [
        'type' => 'friend_response',
        'from' => $currentUser,
        'content' => "$currentUser 已拒绝您的好友请求。",
        'status' => 'processed',
        'timestamp' => date('Y-m-d H:i:s')
    ];
    file_put_contents($systemMessagesFile, json_encode($systemMessages));
}

// 响应
echo $action === 'accept' ? '好友请求已接受！' : '好友请求已拒绝！';